package com.jdk.learn.juc._09threadpool;

import java.time.Duration;
import java.time.Instant;
import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by ricky
 * on 2018/2/2.
 */
public class ForkJoinDemo {
    private static Random rand = new Random();
    private static long t = System.currentTimeMillis();
    public static void main(String[] args) throws Exception {
        Instant start=Instant.now();
        ForkJoinPool pool=new ForkJoinPool();
        //  1000000000L    5878  并行情况    7019 for循环
        //  100000000L    1028     1074
        //  10000000000L   55070   64376
        Long invoke = pool.invoke(new FJSum(0L, 10000000000L));
        System.out.println(invoke);
        Instant end=Instant.now();
        System.out.println(Duration.between(start,end).toMillis());

    }
}

/**
 * 计算
 */
class FJSum extends RecursiveTask<Long> {

    private  Long start,end;
    private static final Long threadsold=10000000000L;//阈值

    public FJSum(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long len=end-start;
        Long sum=0L;
        if (len <= threadsold) {
            for (Long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {
            Long mid=(start+end)/2;
            FJSum left=new FJSum(start,mid);
            left.fork();
            FJSum right=new FJSum(mid+1,end);
            right.fork();

            try {
                return left.get()+right.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}